import mysql.connector

try:
    mydb = mysql.connector.connect(
        host="localhost",         # MySQL服务器的地址
        port=3306,          # 端口，默认3306
        user="root",     # MySQL用户名
        password="123456",   # 数据库密码
        database="python_test"  # 要连接的数据库名
    )
    
    mycursor = mydb.cursor()
    
    # mycursor.execute("CREATE DATABASE python_test")
    # print("数据库 'python_test' 数据库已创建成功!")
    # mycursor.execute("CREATE TABLE pythondemo (id INT,date VARCHAR(255), num VARCHAR(255), name VARCHAR(255));")
    # print("数据库 'pythondemo' 创建表成功!")

    # mycursor.execute("INSERT INTO pythondemo (id, date, num, name) VALUES "
    #              "(1, '2024-10-15 10:27:00', '000001', '设备A'), "
    #              "(2, '2024-10-15 10:27:00', '000002', '设备B'), "
    #              "(3, '2024-10-15 10:27:00', '000003', '设备3');")
    # print("数据库插入数据成功!")

    # mycursor.execute("update pythondemo set name='设备6' where id= 3;")
    # print("更新数据语句成功!")

    mycursor.execute("SELECT id, name FROM pythondemo;")
    results: tuple = mycursor.fetchall()
    for row in results:
        print(f"ID: {row[0]}, 名称: {row[1]}")  # 打印每一行的id和name

    # mycursor.execute("delete from pythondemo where id= 3;")
    # print("删除数据语句成功!")

except mysql.connector.Error as err:
    print(f"发生错误: {err}")

finally:
    if 'mycursor' in locals():
        mycursor.close()
    if 'mydb' in locals() and mydb.is_connected():
        mydb.close()
        print("数据库连接已关闭.")
